//
//  RCSystemService.m
//  CPICApp
//
//  Created by sinosoft on 13-3-26.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "RCSystemService.h"
#import "config.h"
#import "RCAssertUtils.h"

#define rckSYSTEM_VERSION @"rckSYSTEM_VERSION"

@implementation RCSystemService

+(BOOL) isOldVersionCompareWithVersionFromServer:(NSString*) versionFromServer
{
    @synchronized(self)
    {
       RCAssertArgNotEmpty(versionFromServer);
        NSString *version=[[NSUserDefaults standardUserDefaults] objectForKey:rckSYSTEM_VERSION];
        
        [[NSUserDefaults standardUserDefaults] setObject:IPAD_VERSION forKey:rckSYSTEM_VERSION];
        version=[[NSUserDefaults standardUserDefaults] objectForKey:rckSYSTEM_VERSION];
        
        NSLog(@"开始判断当前系统版本是否比服务器版本低,当前版本:%@,服务器上的版本:%@",version,versionFromServer);
        if (![version isNotEmpty]) {
            NSLog(@"本地未保存系统版本,返回结果:当前系统版本比服务器版本低");
            return YES;
        }
        else
        {
            NSArray *versionParts=[version componentsSeparatedByString:@"."];
            NSArray *versionFromServerParts=[versionFromServer componentsSeparatedByString:@"."];
            
            if (versionParts.count<=0) {
                NSLog(@"本地保存的系统版本格式不规范,返回结果当前系统版本比服务器版本低");
            }
            
        BOOL isOldVersion=NO;
        for (int i=0; i<versionParts.count; i++) {
            if (versionFromServerParts.count<i+1) {
                isOldVersion=NO;
                break;
            }
            NSString *oldVersionPart=[versionParts objectAtIndex:i];
            NSString *serverVersionPart=[versionFromServerParts objectAtIndex:i];
            NSComparisonResult comparisonResult=[oldVersionPart compare:serverVersionPart];
            if (comparisonResult==NSOrderedAscending) {
                isOldVersion=YES;
                break;
            }
            else if (comparisonResult==NSOrderedDescending)
            {
                isOldVersion=NO;
                break;
            }
        }
        if (isOldVersion) {
            NSLog(@"返回比较结果:当前系统版本比服务器版本低");
        }
        else
        {
            NSLog(@"返回比较结果:当前系统版本不比服务器版本低");
        }
return isOldVersion;
        }
    }
}
+(void) replaceNewVersion:(NSString*) newVersion{
    @synchronized(self){
        NSLog(@"更新版本号：%@",newVersion);
        NSLog(@"%@",newVersion);
        [[NSUserDefaults standardUserDefaults] setObject:newVersion forKey:rckSYSTEM_VERSION];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

+(NSString*) currentVersion{
    @synchronized(self){
        NSString *strVersion=[[NSUserDefaults standardUserDefaults] objectForKey:rckSYSTEM_VERSION];
        if (strVersion.length==0) {
            return IPAD_VERSION;
        }
        else
        {
            return strVersion;
        }
    }
}

@end
